package com.bw.controller.customer;



import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.linkMan.Linkman;
import com.bw.req.CustForm;
import com.bw.req.LoginCust;
import com.bw.resp.ResponseResult;
import com.bw.service.customer.IPiCustomerService;
import com.bw.service.customer.impl.PiCustomerServiceImpl;
import com.bw.service.linkman.ILinkmanService;
import com.bw.utils.auth.JwtUtils;
import com.bw.utils.auth.RsaUtils;
import com.bw.utils.auth.UserInfo;
import com.bw.utils.excel.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import net.sf.excelutils.ExcelUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.bw.entity.customer.PiCustomer;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yinxurui
 * @since 2020-06-16
 */
@RestController
@RequestMapping("customer")
public class PiCustomerController {

    @Autowired
    private PiCustomerServiceImpl customerService;

    @Autowired
    private ILinkmanService linkmanService;

    @Autowired
    private IPiCustomerService piCustomerService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Value("${keyPath}")
    private String keyPath;

    private final Logger logger= LoggerFactory.getLogger(PiCustomerController.class);
    /**
     * @Description:
     * @Author: 尹绪瑞
     * @Date: 2020/6/20 8:42
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("findLink/{id}")
    public  ResponseResult findLink(@PathVariable("id")long id){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("customerId",id);

            result.setResult(linkmanService.list(wrapper));
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败" + e.toString());
        }
        return result;
    }
    /**
     * @Description:
     * @Author: 尹绪瑞
     * @Date: 2020/6/20 8:42
     * @param response:
     * @return: void
     **/
    @GetMapping("exportExcel")
    public  void exportExcel(HttpServletResponse response) throws Exception {
        logger.info("客户信息导出");
        List<PiCustomer> list=customerService.list();
        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("客户数据".getBytes(),"iso-8859-1")+".xls");
        ClassPathResource classPathResource=new ClassPathResource("xls/customer.xls");
        InputStream inputStream=classPathResource.getInputStream();
        ExcelUtils.addValue("list",list);
        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());
        logger.info("客户信息导出完成");
    }
    /**
     * @Description:
     * @Author: 尹绪瑞
     * @Date: 2020/6/20 8:42
     * @param file:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("importExcel")
    public  ResponseResult importExcel(MultipartFile file){
        logger.info("客户信息导入开始");
            ResponseResult result=ResponseResult.SUCCESS();
            try {
                //获取文件后缀
                String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
                List<Map> mapList= ExcelUtil.readExcel(ext,file.getInputStream());//读取excel存到list集和
                System.out.println(mapList);
                String jsonString= JSON.toJSONString(mapList);//将集和转成js字符串
                List<PiCustomer> list=JSON.parseArray(jsonString,PiCustomer.class);//将json字符串转成集合
                customerService.saveBatch(list);//添加
                logger.info("客户信息导入成功");

            }catch (Exception e){
                logger.error("客户信息导入失败"+e.toString());
                result.setSuccess(false);
                result.setMessage("导入客户失败:" + e.toString());

            }
        logger.info("客户信息导入完成");
            return  result;
    }

    /**分页多条件
     * @param page:
     * @param size:
     * @param custForm:
     * @Description:
     * @Author: 尹绪瑞
     * @Date: 2020/6/18 14:21
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody CustForm custForm) {
        logger.info("查询客户信息");
        ResponseResult result = ResponseResult.SUCCESS();
        QueryWrapper wrapper = new QueryWrapper();
        try {
            PageHelper.startPage(page, size);
            if (custForm.getName() != null && custForm.getName() != "") {
                wrapper.like("name", custForm.getName());
            }
            if (custForm.getStartDate() != null && custForm.getEndDate() != null) {
                wrapper.between("cooperDate", custForm.getStartDate(), custForm.getEndDate());
            }
            List<PiCustomer> list = customerService.list(wrapper);
            PageInfo pageInfo = new PageInfo(list);
            result.setResult(pageInfo);
            logger.info("查询成功");
        } catch (Exception e) {
            logger.error("查询失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败" + e.toString());
        }
        return result;
    }
       /**查询单个
        * @Description:
        * @Author: 尹绪瑞
        * @Date: 2020/6/18 14:22
        * @param id:
        * @return: com.bw.resp.ResponseResult
        **/
    @GetMapping("find/{id}")
    public ResponseResult find(@PathVariable("id") long id) {
        logger.info("查询单个客户信息");
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            result.setResult(customerService.getById(id));
        } catch (Exception e) {
            logger.error("查询单个失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("获取失败" + e.toString());
        }
        return result;
    }

    /**
     * @Description:查询客户信息
     * @Author: 周明丽
     * @Date: 2020/7/1 19:09

     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("getList")
    public ResponseResult getList() {
        logger.info("查询单个客户信息");
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            List<PiCustomer> list = customerService.list();
            result.setResult(list);
        } catch (Exception e) {
            logger.error("查询单个失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("获取失败" + e.toString());
        }
        return result;
    }
   /**通过id删除
    * @Description:
    * @Author: 尹绪瑞
    * @Date:  14:23
    * @param id:
    * @return: com.bw.resp.ResponseResult
    **/
    @GetMapping("del/{id}")
    public ResponseResult del(@PathVariable("id") long id) {
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            customerService.removeById(id);
            result.setMessage("删除成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除失败" + e.toString());
        }
        return result;
    }
    /**添加
     * @Description:
     * @Author: 尹绪瑞
     * @Date: 2020/6/18 14:23
     * @param customer:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("save")
    public ResponseResult save(@RequestBody PiCustomer customer) {
        logger.info("保存客户信息");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            this.customerService.saveOrUpdate(customer);
            result.setMessage("保存成功");
        } catch (Exception e) {
            logger.error("保存失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("保存失败" + e.toString());
        }

        return result;
    }


    /**
     * @Description:登录
     * @Author: 周明丽
     * @Date: 2020/6/25 14:34
     * @param :
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("login")
    public ResponseResult sendCode(@RequestBody LoginCust loginCust){
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            String code=redisTemplate.boundValueOps("Y:"+loginCust.getTel()).get();
            if(null==code){
                result.setSuccess(false);
                result.setMessage("验证码过期");
                return result;
            }
            if(!code.equals(loginCust.getCode())){
                result.setSuccess(false);
                result.setMessage("验证码错误");
                return result;
            }
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("tel",loginCust.getTel());
            Linkman linkman = linkmanService.getOne(queryWrapper);
            PiCustomer piCustomer = customerService.getById(linkman.getCustomerId());

            PrivateKey privateKey = RsaUtils.getPrivateKey(keyPath+"rsa.pri");//获取私钥

            UserInfo userInfo=new UserInfo(); //当前登录用户信息
            userInfo.setId(piCustomer.getId());
            userInfo.setUsername(piCustomer.getName());

            String token = JwtUtils.generateToken(userInfo,privateKey,30);//颁发令牌

            Map mapinfo=new HashMap();
            mapinfo.put("user",piCustomer);
            mapinfo.put("linkman",linkman);
            mapinfo.put("token",token);

            result.setMessage("登录成功");
            result.setResult(mapinfo);

        }catch (Exception e){
            result=ResponseResult.FAIL();
           // result.setResult("发送失败"+e.toString());
        }
        return result;
    }

    /**
     * @Description:发送验证码
     * @Author: 周明丽
     * @Date: 2020/6/25 14:34
     * @param tel:
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("sendCode/{tel}")
    public ResponseResult sendCode(@PathVariable("tel") String tel){
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            result = piCustomerService.sendCode(tel);
        }catch (Exception e){
            result=ResponseResult.FAIL();
            // result.setResult("发送失败"+e.toString());
        }
        return result;
    }


}
